#version 330 core

in vec2 TexCoords;

uniform float Time;
uniform vec2 MousePos;
uniform vec2 Size;
uniform sampler2D image;
uniform sampler2D imageNoise;
uniform sampler2D imageNoise2;
uniform float DrawBg;
uniform sampler2D Color;

out vec4 FragColor;

float MAX_RADIUS = 2.0;
float HASHSCALE1 = 0.1031;
vec3 HASHSCALE3 = vec3(0.1031, 0.1030, 0.0973);
	
float hash12(vec2 p)
{
	vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);
	p3 += dot(p3, p3.yzx + 19.19);
	return fract((p3.x + p3.y) * p3.z);
}

vec2 hash22(vec2 p)
{
	vec3 p3 = fract(vec3(p.xyx) * HASHSCALE3);
	p3 += dot(p3, p3.yzx + 19.19);
	return fract((p3.xx + p3.yz) * p3.zy);
}

void main()
{
	
	float resolution = 1.0;//10.0 * exp2(-3.0 / (1.0 / Size).x);
	vec2 uv = TexCoords.xy;// / (1.0 / Size).y * resolution;
	vec2 p0 = floor(uv); 
	
	vec2 circles = vec2(0.0);
	for(float j = -MAX_RADIUS; j <= MAX_RADIUS; ++j){
		for(float i = -MAX_RADIUS; i <= MAX_RADIUS; ++i){
			vec2 pi = p0 + vec2(i, j);
			vec2 hsh = hash22(pi);
			vec2 p = pi + hash22(hsh);
			float t = fract(0.3 * Time + hash12(hsh));
			vec2 v = p - uv;
			float d = length(v) - (float(MAX_RADIUS) + 1.0) * t;
			
			float h =1e-3;
			float d1 = d - h;
			float d2 = d + h;
			float p1 = sin(31.0*d1)*smoothstep(-0.6,-0.3,d1)*smoothstep(0.0,-0.3,d1);
			float p2 = sin(31.0*d2)*smoothstep(-0.6,-0.3,d2)*smoothstep(0.0,-0.3,d2);
			circles += 0.5 * normalize(v) * ((p2-p1)/(2.0*h)*(1.0-t)*(1.0-t));
		}
	}
	
	circles /= float((MAX_RADIUS*2.0+1.0)*(MAX_RADIUS*2.0+1.0));
	float intensity = mix(0.01,0.15,smoothstep(0.1,0.6,abs(fract(0.05*Time+0.5)*2.0-1.0)));
	vec3 n = vec3(circles, sqrt(1.0-dot(circles, circles)));
	vec3 color = texture2D(image, uv/resolution - intensity*n.xy).rgb;// + 5.0*pow(clamp(dot(n, n).x, 0.0, 1.0), n);
	
	FragColor = vec4(color, 1.0);
	
}
